package com.maslyk.invitation.jsfcontroller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.faces.event.ActionEvent;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;

import org.apache.myfaces.component.html.ext.HtmlDataTable;

import com.maslyk.invitation.BeanService;
import com.maslyk.invitation.PageTools;
import com.maslyk.invitation.entitybean.Auditlog;
import com.maslyk.invitation.entitybean.Salesman;
import com.maslyk.invitation.enums.ViewIdentityEnum;
import com.maslyk.invitation.exception.LogicalException;
import com.maslyk.invitation.page.GlobalMessage;
import com.maslyk.invitation.service.PersistenceService;
import com.maslyk.invitation.to.AuditLogSearchCriteria;
import com.maslyk.invitation.to.CurrentUserTO;
import com.maslyk.invitation.to.SessionDataTO;
import com.maslyk.invitation.to.UserPassword;

public class SalesmanController
{
	private PersistenceService persistenceService;
	
    public SalesmanController()
    {        
    }

    private HtmlDataTable salesmanListDataTable;

    private UserPassword userPassword = new UserPassword();
    
    private AuditLogSearchCriteria auditCriteria = new AuditLogSearchCriteria();
    private List<Auditlog> auditList = new ArrayList<Auditlog>();
    
    public HtmlDataTable getSalesmanListDataTable()
    {
        return salesmanListDataTable;
    }

    public void setSalesmanListDataTable(HtmlDataTable salesmanList)
    {
        this.salesmanListDataTable = salesmanList;
    }

    public String addSalesman() throws LogicalException, Exception
    {
        Salesman salesMan = (Salesman) BeanService.getSessionScopeBean("salesmanBean");
        

        salesMan.setRegistrationdate(new Date());

        if(salesMan.getPersonid().getId() == null)
        	persistenceService.createPerson(salesMan.getPersonid());

        if(salesMan.getId() == null)
        	persistenceService.createSalesman(salesMan);
        else
        	persistenceService.editSalesman(salesMan);
        
        SessionDataTO.setCurrentView(ViewIdentityEnum.SALESMAN_LIST);
        BeanService.putSessionScopeBean("salesmanBean", null);
        BeanService.putSessionScopeBean("personBean", null);

        return null;
    }

    public List<Salesman> getSalesmanList() throws Exception
    {
        try
		{
			return persistenceService.getSalesmanList();
		} catch (Exception e)
		{
			throw e;
		}
    }

    public List<SelectItem> getSalesmanItems() throws Exception
    {
        List<SelectItem> list = new ArrayList<SelectItem>();

        for (Salesman sal : getSalesmanList())
        {
        	if(sal.getLogin().equals("automat") || sal.isInactive())
        		continue;
        	
            list.add(new SelectItem(sal, sal.toString(), sal.getLogin()));
        }

        return list;
    }

    public String removeSalesman()
    {
        Salesman entity = (Salesman) salesmanListDataTable.getRowData();

        if(entity == null)
            return null;
        
        try
        {
        	persistenceService.destroySalesman(entity);
        }
        catch (Exception ex)
        {
            PageTools.addMessage(ex);
            Logger.getLogger(SalesmanController.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
        SessionDataTO.setCurrentView(ViewIdentityEnum.SALESMAN_LIST);
        return null;
    }

    public String updateSalesman()
    {
        Salesman entity = (Salesman) salesmanListDataTable.getRowData();

        if(entity == null)
            return null;
        
        BeanService.putSessionScopeBean("salesmanBean", entity);

        SessionDataTO.setCurrentView(ViewIdentityEnum.SALESMAN_FORM);
        return null;
    }

    @SuppressWarnings("unchecked")
	public void changePermissionsListener(ValueChangeEvent changeEvent)
    {
        List<String> _permissions = (List<String>) changeEvent.getNewValue();
        Salesman salesMan = (Salesman) BeanService.getSessionScopeBean("salesmanBean");

        if(_permissions == null || _permissions.isEmpty())
            return;

        String permissions = "";

        for(String permission : _permissions)
            permissions += permission.toString()+",";

        salesMan.setPermissions(permissions);
    }

    public String addGlobalMessage()
    {
        GlobalMessage globalMessageRequest = (GlobalMessage) BeanService.getSessionScopeBean("globalMessageRequest");
        CurrentUserTO currentUser = (CurrentUserTO) BeanService.getSessionScopeBean("currentUserTO");
        globalMessageRequest.setFromUser(currentUser.getCurrentSalesman().getPersonid().getFirstname()+" "+currentUser.getCurrentSalesman().getPersonid().getSurname());
        BeanService.putApplicationScopeBean("globalMessage", globalMessageRequest);
        BeanService.putSessionScopeBean("globalMessageRequest", null);
        SessionDataTO.setCurrentView(ViewIdentityEnum.ORDER_LIST);
        return null;
    }

    public void clearGlobalMessage(ActionEvent event)
    {
        BeanService.putApplicationScopeBean("globalMessage", null);
    }

    public UserPassword getUserPassword()
    {
        return userPassword;
    }

    public void setUserPassword(UserPassword userPassword)
    {
        this.userPassword = userPassword;
    }

    public String changeSalesmanPassword() throws Exception
    {
        Salesman salesMan = (Salesman) BeanService.getSessionScopeBean("salesmanBean");

        if(userPassword.isValid(salesMan.getPassword()))
        {
            salesMan.setPassword(userPassword.getNewEncodedPassword());
            persistenceService.editSalesman(salesMan);
        }
        else
        {
            PageTools.addFieldMessages("invalidPassword", "Podano nieprawidlowe dane.");
        }
        
        return null;
    }
    
    public List<Auditlog> getAuditList(){
    	return auditList;
    }

	public AuditLogSearchCriteria getAuditCriteria() {
		return auditCriteria;
	}

	public void setAuditCriteria(AuditLogSearchCriteria auditCriteria) {
		this.auditCriteria = auditCriteria;
	}
	
	public void searchForAuditLog(ActionEvent event)
	{
		auditList = persistenceService.getAuditList(auditCriteria);
	}

	public void setPersistenceService(PersistenceService persistenceService) {
		this.persistenceService = persistenceService;
	}
}
